<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Drawing in PyQt4</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PyQt, PyQt4, tutorial, Python, drawing, Linux">
<meta name="description" content="In this part of the PyQt4 tutorial, we do
some drawing.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Drawing in PyQt4</h1>


<p>
Drawing is used, when we want to change or enhance an existing widget. 
Or if we are creating a custom widget from scratch.
To do the drawing, we use the drawing API provided by the PyQt4 toolkit. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
The drawing is done within the <code>paintEvent()</code> method. 
The drawing code is placed between the <code>begin()</code> and 
<code>end()</code> methods of the <code>QtGui.QPainter</code> object.
</p>

<h2>Drawing text</h2>

<p>
We begin with drawing some Unicode text onto the window client area.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

In this example, we draw text in Russian azbuka.

author: Jan Bodnar
website: zetcode.com 
last edited: September 2011
"""

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.text = u'\u041b\u0435\u0432 \u041d\u0438\u043a\u043e\u043b\u0430\
\u0435\u0432\u0438\u0447 \u0422\u043e\u043b\u0441\u0442\u043e\u0439: \n\
\u0410\u043d\u043d\u0430 \u041a\u0430\u0440\u0435\u043d\u0438\u043d\u0430'

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Draw text')
        self.show()

    def paintEvent(self, event):

        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawText(event, qp)
        qp.end()
        
    def drawText(self, event, qp):
      
        qp.setPen(QtGui.QColor(168, 34, 3))
        qp.setFont(QtGui.QFont('Decorative', 10))
        qp.drawText(event.rect(), QtCore.Qt.AlignCenter, self.text)        
                
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
In our example, we draw some text in Azbuka. 
The text is vertically and horizontally aligned.
</p>

<pre class="explanation">
def paintEvent(self, event):
</pre>

<p>
Drawing is done within a paint event.
</p>

<pre class="explanation">
qp = QtGui.QPainter()
qp.begin(self)
self.drawText(event, qp)
qp.end()
</pre>

<p>
The <code>QtGui.QPainter</code> class is responsible for all the low-level painting. 
All the painting methods go between <code>begin()</code>
and <code>end()</code> methods. The actual painting is delegated to the
drawText() method.
</p>

<pre class="explanation">
qp.setPen(QtGui.QColor(168, 34, 3))
qp.setFont(QtGui.QFont('Decorative', 10))
</pre>

<p>
Here we define pen and font, which we use to draw the text.
</p>

<pre class="explanation">
qp.drawText(event.rect(), QtCore.Qt.AlignCenter, self.text)
</pre>

<p>
The <code>drawText()</code> method draws text on the window. 
The <code>rect()</code> method of the paint event returns the rectangle 
that needs to be updated.
</p>

<br>
<img src="/img/gui/pyqt4/drawtext.png" alt="Drawing text">
<div class="figure">Figure: Drawing text</div>



<h2>Drawing points</h2>

<p>
A point is the most simple graphics object, that can be drawn. 
It is a small spot on the window.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

In the example, we draw randomly 1000 red points 
on the window.

author: Jan Bodnar
website: zetcode.com 
last edited: September 2011
"""

import sys, random
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Points')
        self.show()

    def paintEvent(self, e):

        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawPoints(qp)
        qp.end()
        
    def drawPoints(self, qp):
      
        qp.setPen(QtCore.Qt.red)
        size = self.size()
        
        for i in range(1000):
            x = random.randint(1, size.width()-1)
            y = random.randint(1, size.height()-1)
            qp.drawPoint(x, y)     
                
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
In our example, we draw randomly 1000 red points on the client area. 
</p>

<pre class="explanation">
qp.setPen(QtCore.Qt.red)
</pre>

<p>
We set the pen to red color. We use a predefined color constant. 
</p>

<pre class="explanation">
size = self.size()
</pre>

<p>
Each time we resize the window, a paint event is generated. We get the 
current size of the window with the <code>size()</code> method.
We use the size of the window to distribute the points all over the
client area of the window. 
</p>

<pre class="explanation">
qp.drawPoint(x, y) 
</pre>

<p>
We draw the point with the <code>drawPoint()</code> method.
</p>

<br>
<img src="/img/gui/pyqt4/points.png" alt="Points">
<div class="figure">Figure: Points</div>


<h2>Colors</h2>

<p>
A color is an object representing a combination of Red, Green, and 
Blue (RGB) intensity values. Valid RGB values are in the range 0 to 255. 
We can define a color in various ways. The most common are RGB decimal 
values or hexadecimal values. We can also use an RGBA value, which 
stands for Red, Green, Blue, Alpha. Here we add some extra information, regarding
transparency. Alpha value of 255 defines full opacity, 0 is for full 
transparency, eg the color is invisible.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

This example draws three rectangles in three
different colors. 

author: Jan Bodnar
website: zetcode.com 
last edited: September 2011
"""

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.setGeometry(300, 300, 350, 100)
        self.setWindowTitle('Colors')
        self.show()

    def paintEvent(self, e):

        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        qp.end()
        
    def drawRectangles(self, qp):
      
        color = QtGui.QColor(0, 0, 0)
        color.setNamedColor('#d4d4d4')
        qp.setPen(color)

        qp.setBrush(QtGui.QColor(200, 0, 0))
        qp.drawRect(10, 15, 90, 60)

        qp.setBrush(QtGui.QColor(255, 80, 0, 160))
        qp.drawRect(130, 15, 90, 60)

        qp.setBrush(QtGui.QColor(25, 0, 90, 200))
        qp.drawRect(250, 15, 90, 60)
              
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
In our example, we draw 3 colored rectangles.
</p>

<pre class="explanation">
color = QtGui.QColor(0, 0, 0)
color.setNamedColor('#d4d4d4')
</pre>

<p>
Here we define a color using hexadecimal notation.
</p>


<pre class="explanation">
qp.setBrush(QtGui.QColor(200, 0, 0))
qp.drawRect(10, 15, 90, 60)
</pre>

<p>
Here we define a brush and draw a rectangle. A <b>brush</b> 
is an elementary graphics object, which is used to draw the 
background of a shape. The <code>drawRect()</code> method accepts 
four parameter. The first two are x, y 
values on the axis. The third and fourth parameters are width and height of 
the rectangle. The method draws a rectangle using current pen and current
brush.
</p>


<br>
<img src="/img/gui/pyqt4/colors.png" alt="Colors">
<div class="figure">Figure: Colors</div>


<h2>QtGui.QPen</h2>

<p>
<code>QtGui.QPen</code> is an elementary graphics object. It is used to draw lines, 
curves and outlines of rectangles, ellipses, polygons or other shapes.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

In this example we draw 6 lines using
different pen styles. 

author: Jan Bodnar
website: zetcode.com 
last edited: September 2011
"""

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.setGeometry(300, 300, 280, 270)
        self.setWindowTitle('Pen styles')
        self.show()

    def paintEvent(self, e):

        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()
        
    def drawLines(self, qp):
      
        pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)

        qp.setPen(pen)
        qp.drawLine(20, 40, 250, 40)

        pen.setStyle(QtCore.Qt.DashLine)
        qp.setPen(pen)
        qp.drawLine(20, 80, 250, 80)

        pen.setStyle(QtCore.Qt.DashDotLine)
        qp.setPen(pen)
        qp.drawLine(20, 120, 250, 120)

        pen.setStyle(QtCore.Qt.DotLine)
        qp.setPen(pen)
        qp.drawLine(20, 160, 250, 160)

        pen.setStyle(QtCore.Qt.DashDotDotLine)
        qp.setPen(pen)
        qp.drawLine(20, 200, 250, 200)

        pen.setStyle(QtCore.Qt.CustomDashLine)
        pen.setDashPattern([1, 4, 5, 4])
        qp.setPen(pen)
        qp.drawLine(20, 240, 250, 240)
              
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>


<p>
In our example, we draw six lines. The lines are drawn in six different pen styles. 
There are five predefined pen styles.
We can create also custom pen styles. The last line is drawn using custom pen style.
</p>

<pre class="explanation">
pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
</pre>

<p>
We create a <code>QtGui.QPen</code> object. The color is black. The width 
is set to 2 pixels, so that we can see the differences between the pen 
styles. The <code>QtCore.Qt.SolidLine</code> is one of the predefined pen styles.
</p>


<pre class="explanation">
pen.setStyle(QtCore.Qt.CustomDashLine)
pen.setDashPattern([1, 4, 5, 4])
qp.setPen(pen)
</pre>

<p>
Here we define a custom pen style. We set a <code>QtCore.Qt.CustomDashLine</code>
pen style and call a <code>setDashPattern()</code> method. The list of numbers defines a style. 
There must be an even number of numbers. Odd numbers define a dash, even numbers space. 
The greater the number, the greater the space or the dash. Our pattern is 1px dash 4px 
space 5px dash 4px space etc.
</p>

<br>
<img src="/img/gui/pyqt4/penstyles.png" alt="Pen Styles">
<div class="figure">Figure: Pen Styles</div>


<h2>QtGui.QBrush</h2>

<p>
<code>QtGui.QBrush</code> is an elementary graphics object. It is 
used to paint the background of graphics shapes,
such as rectangles, ellipses or polygons. A brush can be of three 
different types. A predefined brush a gradient or a texture pattern.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial 

This example draws 9 rectangles in different
brush styles.

author: Jan Bodnar
website: zetcode.com 
last edited: September 2011
"""

import sys
from PyQt4 import QtGui, QtCore


class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):      

        self.setGeometry(300, 300, 355, 280)
        self.setWindowTitle('Brushes')
        self.show()

    def paintEvent(self, e):

        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawBrushes(qp)
        qp.end()
        
    def drawBrushes(self, qp):
      
        brush = QtGui.QBrush(QtCore.Qt.SolidPattern)
        qp.setBrush(brush)
        qp.drawRect(10, 15, 90, 60)

        brush.setStyle(QtCore.Qt.Dense1Pattern)
        qp.setBrush(brush)
        qp.drawRect(130, 15, 90, 60)

        brush.setStyle(QtCore.Qt.Dense2Pattern)
        qp.setBrush(brush)
        qp.drawRect(250, 15, 90, 60)

        brush.setStyle(QtCore.Qt.Dense3Pattern)
        qp.setBrush(brush)
        qp.drawRect(10, 105, 90, 60)

        brush.setStyle(QtCore.Qt.DiagCrossPattern)
        qp.setBrush(brush)
        qp.drawRect(10, 105, 90, 60)

        brush.setStyle(QtCore.Qt.Dense5Pattern)
        qp.setBrush(brush)
        qp.drawRect(130, 105, 90, 60)

        brush.setStyle(QtCore.Qt.Dense6Pattern)
        qp.setBrush(brush)
        qp.drawRect(250, 105, 90, 60)

        brush.setStyle(QtCore.Qt.HorPattern)
        qp.setBrush(brush)
        qp.drawRect(10, 195, 90, 60)

        brush.setStyle(QtCore.Qt.VerPattern)
        qp.setBrush(brush)
        qp.drawRect(130, 195, 90, 60)

        brush.setStyle(QtCore.Qt.BDiagPattern)
        qp.setBrush(brush)
        qp.drawRect(250, 195, 90, 60)
              
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>


<p>
In our example, we draw nine different rectangles.
</p>

<pre class="explanation">
brush = QtGui.QBrush(QtCore.Qt.SolidPattern)
qp.setBrush(brush)
qp.drawRect(10, 15, 90, 60)
</pre>

<p>
We define a brush object. Set it to the painter object. And draw the 
rectangle calling the <code>drawRect()</code> method.
</p>

<br>
<img src="/img/gui/pyqt4/brushes.png" alt="Brushes">
<div class="figure">Figure: Brushes</div>


<hr class="btm">


<p>
In this part of the PyQt4 tutorial, we did some basic painting.
</p>


<br>
<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 21, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
